import {Component} from 'react';
import {connect} from 'react-redux';
import axios from 'axios';
import * as Notification from 'modules/notification/actions';
import Session from 'modules/auth/session';
import styled from "styled-components";
import {Button, Empty, Input, Modal, PageHeader, Select, Table} from 'antd';

const {Option} = Select;

const ButtonGroup = Button.Group;
const Outer = styled.div`
  border:1px solid #ececec;
  margin:20px;
   box-shadow: 3px 3px 6px rgba(0,0,0,0.1), 3px 3px 6px rgba(0,0,0,0.2);
`;


const Conten = styled.div`
  margin: 20px;
  box-sizing:border-box;
`;
const ContenTiTle = styled.div`
padding:1px;
 background:#f1f1f1;
`;
const ContenList = styled.div`
  display:flex;
  justify-content: center;
  align-items: center;
  margin: 10px auto;
`;
const CenterName = styled.div`
  width:180px;
  font-size:14px;
  color:#000;
  text-align:right;
  padding-right:15px;
`;
const CenterInputOuter = styled.div`
  width:400px;
  font-size:14px;
  color:#000;
`;

const SecurityAlgotithmsIdBaseArray = [3, 2, 1]
const priorityArray = [1, 2, 3]

class Collection extends Component {
    state = {
        search: '',
        document: {
            action: '',
            visible: false,
            dimmed: false
        },
        confirm: {
            visible: false,
            imsi: ''
        },
        view: {
            visible: false,
            disableOnClickOutside: false,
            imsi: ''
        },
        visible: false,
        modelTitle: '新增安全算法配置',
        configData: {},
        selectedRowKeys: [], // Check here to configure the default column
        loading: false,
        SecurityData: [],
        SecurityAlgotithmsId: '',
        priority: '',
        ciperingAlgorithms: 'ciperingAlgorithms',
        integrityAlgorithms: '',
        usePriorityArray: []
    };


    onSelectChange = selectedRowKeys => {
        this.setState({selectedRowKeys});
    };


    componentWillMount() {

        const {dispatch} = this.props
        let $this = this
        const sessionData = new Session();
        const csrf = ((sessionData || {}).session || {}).csrfToken;
        const authToken = ((sessionData || {}).session || {}).authToken;
        let headers = {'X-CSRF-TOKEN': csrf}
        if (authToken) {
            headers['Authorization'] = "Bearer " + authToken
        }

        axios({
            baseURL: '/api/db',
            headers: headers,
            method: "get",
            url: '/amf',
            params: {},
            // data
        }).then(res => {
            var configData = res.data[0].config
            $this.setState({
                    configData: res.data[0],
                    SecurityData: configData.SecurityData || []
                }
            )

        })
    }

    getSData = () => {
        const {dispatch} = this.props
        let $this = this
        const sessionData = new Session();
        const csrf = ((sessionData || {}).session || {}).csrfToken;
        const authToken = ((sessionData || {}).session || {}).authToken;
        let headers = {'X-CSRF-TOKEN': csrf}
        if (authToken) {
            headers['Authorization'] = "Bearer " + authToken
        }

        axios({
            baseURL: '/api/db',
            headers: headers,
            method: "get",
            url: '/amf',
            params: {},
            // data
        }).then(res => {
            var configData = res.data[0].config
            $this.setState({
                    configData: res.data[0],
                    SecurityData: configData.SecurityData || []

                }
            )

            dispatch(Notification.success({
                title: '提示',
                message: `安全算法配置列表刷新成功！`
            }));
        })
    }

    handleOk = e => {
        let $this = this

        let editorBol = false
        if (this.state.modelTitle == '修改安全算法配置') {
            editorBol = true
        }
        const {dispatch} = this.props
        let sendData = JSON.parse(JSON.stringify(this.state.configData))
        sendData.config.SecurityData = sendData.config.SecurityData || []
        let sendLine = {}
        sendLine.ciperingAlgorithms = this.state.ciperingAlgorithms
        sendLine.integrityAlgorithms = this.state.integrityAlgorithms
        sendLine.SecurityAlgotithmsId = parseInt(this.state.SecurityAlgotithmsId)
        sendLine.priority = this.state.priority

        if (editorBol) {

            sendData.config.SecurityData.forEach(a => {
                if (a.SecurityAlgotithmsId == $this.state.SecurityAlgotithmsId) {
                    a.integrityAlgorithms = sendLine.integrityAlgorithms
                    a.ciperingAlgorithms = sendLine.ciperingAlgorithms
                    a.SecurityAlgotithmsId = sendLine.SecurityAlgotithmsId
                    a.priority = sendLine.priority
                }
            })
        } else {
            sendLine.key = parseInt(Math.random() * 10000000000)
            sendData.config.SecurityData.push(sendLine)
        }

        const sessionData = new Session();
        const csrf = ((sessionData || {}).session || {}).csrfToken;
        const authToken = ((sessionData || {}).session || {}).authToken;
        let headers = {'X-CSRF-TOKEN': csrf}
        if (authToken) {
            headers['Authorization'] = "Bearer " + authToken
        }

        axios({
            baseURL: '/api/db',
            headers: headers,
            method: "PATCH",
            url: '/amf/' + sendData._id,
            data: sendData,
            //
        }).then(res => {
            this.handleCancel()
            var configData = res.data.config
            $this.setState({
                    configData: res.data,
                    SecurityData: configData.SecurityData || []
                }
            )
            dispatch(Notification.success({
                title: '提示',
                message: `安全算法配置配置成功！`
            }));
        })
    }

    showModal = () => {
        this.setState({
            visible: true,
        });
    };


    handleCancel = e => {
        this.setState({
            visible: false,
        });
    };


    _handleChange(e) {
        // 获取 input 元素上的value
        let name = e.target.name;
        let value = e.target.value;
        this.setState({
            [name]: value
        })
    };

    _handleChange1(value) {
        this.setState({
            priority: value
        })
    };

    _handleChange2(value) {
        this.setState({
            integrityAlgorithms: value
        })
    };

    addRow = () => {
        var $this = this
        let newSecurityAlgotithmsId = ''
        let newArray = []
        priorityArray.forEach(a => {
            let nouse = true
            $this.state.SecurityData.forEach(it => {
                if (it.priority == a) {
                    nouse = false
                }
            })
            if (nouse) {
                newArray.push(a)
            }
        })
        SecurityAlgotithmsIdBaseArray.forEach(a => {
            let nodeId = true
            $this.state.SecurityData.forEach(it => {
                if (it.SecurityAlgotithmsId == a) {
                    nodeId = false
                }
            })
            if (nodeId) {
                newSecurityAlgotithmsId = a
            }
        })
        this.setState({
            modelTitle: '新增安全算法配置',
            SecurityAlgotithmsId: newSecurityAlgotithmsId,
            priority: newArray[0],
            ciperingAlgorithms: 'NEA0',
            integrityAlgorithms: 'NIA0',
            usePriorityArray: newArray
        })
        this.showModal()
    }

    editRow = (row, e) => {
        var $this = this

        let newArray = []
        priorityArray.forEach(a => {
            let nouse = true
            $this.state.SecurityData.forEach(it => {
                if (it.priority == a && it.priority != row.priority) {
                    nouse = false
                }
            })
            if (nouse) {
                newArray.push(a)
            }
        })


        this.setState({
            modelTitle: '修改安全算法配置',
            ciperingAlgorithms: row.ciperingAlgorithms,
            integrityAlgorithms: row.integrityAlgorithms,
            SecurityAlgotithmsId: row.SecurityAlgotithmsId,
            priority: row.priority,
            usePriorityArray: newArray
        })
        this.showModal()
    }

    delRow = (row, e) => {
        const {dispatch} = this.props

        var $this = this
        Modal.confirm({
            title: '确定要删除 SecurityAlgotithmsId 为 ' + row.SecurityAlgotithmsId + ' 的数据么？',
            content: '删除后无法找回',
            okText: '确认',
            cancelText: '取消',
            onOk: function () {
                let sendData = JSON.parse(JSON.stringify($this.state.configData))
                let newPData = []
                sendData.config.SecurityData.forEach(a => {
                    if (a.SecurityAlgotithmsId != row.SecurityAlgotithmsId) {
                        newPData.push(a)
                    }
                })
                sendData.config.SecurityData = newPData

                const sessionData = new Session();
                const csrf = ((sessionData || {}).session || {}).csrfToken;
                const authToken = ((sessionData || {}).session || {}).authToken;
                let headers = {'X-CSRF-TOKEN': csrf}
                if (authToken) {
                    headers['Authorization'] = "Bearer " + authToken
                }

                axios({
                    baseURL: '/api/db',
                    headers: headers,
                    method: "PATCH",
                    url: '/amf/' + sendData._id,
                    data: sendData,
                    //
                }).then(res => {
                    $this.handleCancel()
                    var configData = res.data.config
                    $this.setState({
                            configData: res.data,
                            SecurityData: configData.SecurityData || []
                        }
                    )
                    dispatch(Notification.success({
                        title: '提示',
                        message: `安全算法配置删除成功！`
                    }));
                })
            }
        });
    }

    render() {
        let $this = this
        const {loading, selectedRowKeys} = this.state;
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange,
        };
        const hasSelected = selectedRowKeys.length > 0;


        const columns = [
            {
                title: '操作',
                dataIndex: '',
                key: 'y',
                width: 240,
                render: (text, record) => {
                    return (
                        <div>

                            <ButtonGroup>

                                <Button type="primary" onClick={(e) => this.editRow(record, e)}>修改</Button>
                                <Button type="danger" onClick={(e) => this.delRow(record, e)}>删除</Button>
                            </ButtonGroup>
                        </div>
                    )
                },
            },
            {
                title: 'SecurityAlgotithmsId',
                dataIndex: 'SecurityAlgotithmsId',
            },
            {
                title: 'priority',
                dataIndex: 'priority',
            },
            {
                title: 'ciperingAlgorithms',
                dataIndex: 'ciperingAlgorithms',
            },
            {
                title: 'integrityAlgorithms',
                dataIndex: 'integrityAlgorithms',
            },

        ];

        this.state.usePriorityArray.forEach(a => {

        })
        const amfSecurity_infoList = this.state.usePriorityArray.map((ic, index) =>
            <Option key={index} value={ic}>{ic}</Option>
        );
        return (
            <div>
                <PageHeader
                    style={{
                        border: '1px solid rgb(235, 237, 240)',
                    }}
                    title="安全算法配置列表"
                    subTitle="安全算法配置最多只能有3个"
                />
                <Outer>
                    <Conten>
                        <div>
                            <div style={{marginBottom: 16}}>
                                <Button type="success"
                                        title={this.state.SecurityData.length >= 3 ? '安全算法配置最多只能有3个' : ''}
                                        disabled={this.state.SecurityData.length >= 3} onClick={this.addRow}>
                                    新增
                                </Button>
                                <span>&nbsp;&nbsp;</span>
                                <Button type="primary" onClick={this.getSData}>
                                    刷新
                                </Button>
                                <span
                                    style={{marginLeft: 8}}>{hasSelected ? `Selected ${selectedRowKeys.length} items` : ''} </span>
                            </div>
                            <Table locale={
                                {
                                    emptyText: () => {
                                        return (
                                            <Empty
                                                description={
                                                    <span>暂无数据</span>
                                                }
                                            />
                                        )
                                    }
                                }
                            } columns={columns} dataSource={this.state.SecurityData}/>
                        </div>
                    </Conten>
                </Outer>


                <Modal
                    title={this.state.modelTitle}
                    visible={this.state.visible}
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                    okText="确认"
                    width={800}
                    cancelText="取消"
                >
                    <ContenTiTle>
                        <ContenList>
                            <CenterName><strong>参数名</strong></CenterName>
                            <CenterInputOuter>
                                <strong>值</strong>
                            </CenterInputOuter>
                        </ContenList>
                    </ContenTiTle>
                    <ContenList>
                        <CenterName>SecurityAlgotithmsId</CenterName>
                        <CenterInputOuter>
                            <Input
                                disabled={true}
                                value={this.state.SecurityAlgotithmsId}
                                name={'SecurityAlgotithmsId'}
                                onChange={(e) => this._handleChange(e)}
                                maxLength={3}
                                required
                                type={'number'}
                                placeholder={'安全算法实例号，根据顺序填写，目前只支持1~3'}
                                title={'安全算法实例号，根据顺序填写，目前只支持1~3'}
                            /></CenterInputOuter>
                    </ContenList>
                    <ContenList><CenterName>priority</CenterName>
                        <CenterInputOuter title={'优先级，根据实际提供的填写，目前只支持1~3'}>
                            <Select
                                value={this.state.priority}
                                style={{width: 400}}
                                onChange={(e) => this._handleChange1(e)}
                                placeholder={'优先级，根据实际提供的填写，目前只支持1~3'}

                            >
                                {amfSecurity_infoList}
                            </Select>

                        </CenterInputOuter>
                    </ContenList>
                    <ContenList><CenterName>ciperingAlgorithms</CenterName>
                        <CenterInputOuter>
                            <Input
                                name={'ciperingAlgorithms'}
                                disabled={true}
                                required
                                maxLength={3}
                                onChange={(e) => this._handleChange(e)}
                                value={this.state.ciperingAlgorithms}
                                title={'加密算法，根据实际提供的填写，目前只支持NEA0'}
                                placeholder={'加密算法，根据实际提供的填写，目前只支持NEA0'}/>
                        </CenterInputOuter>
                    </ContenList>
                    <ContenList><CenterName>integrityAlgorithms</CenterName>
                        <CenterInputOuter title={'完保算法，根据实际提供的填写，目前只支持NIA0,NIA1,NIA2'}>
                            <Select
                                value={this.state.integrityAlgorithms}
                                style={{width: 400}}
                                onChange={(e) => this._handleChange2(e)}
                                placeholder={'完保算法，根据实际提供的填写，目前只支持NIA0,NIA1,NIA2'}

                            >
                                <Option value="NIA0">NIA0</Option>
                                <Option value="NIA1">NIA1</Option>
                                <Option value="NIA2">NIA2</Option>
                            </Select>
                        </CenterInputOuter>
                    </ContenList>
                </Modal>
            </div>
        )
    }
}

Collection = connect(
    (state) => ({})
)(Collection);

export default Collection;